<template>
	<view>
		<!-- 自定义导航栏 -->
		<nav-bar>
			<template v-if="checkCount===0">
				<view slot="left" class="flex">
					<view v-if="current" hover-class="bg-hover-light" @tap="back" style="width: 60rpx;height: 60rpx;" class="flex align-center justify-center bg-light rounded-circle mr-3">
						<text class="iconfont  icon-fanhui"></text>
					</view>
					<text class="font-md">{{current?current.name:'首页'}}</text>
				</view>
				<view class="flex" slot="right">
					<view hover-class="bg-hover-light" @tap="openAddDialog" style="width: 60rpx;height: 60rpx;" class="flex align-center justify-center bg-light rounded-circle mr-3">
						<text class="iconfont  icon-zengjia"></text>
					</view>
					<view  @tap="openSortDialog" hover-class="bg-hover-light" style="width: 60rpx;height: 60rpx;" class="flex align-center justify-center bg-light rounded-circle mr-3">
						<text class="iconfont icon-gengduo"></text>
					</view>
				</view>
			</template>
			<template v-else>
				<view @click="handleCheckAll(false)" class="font-md ml-3 text-primary" slot="left">取消</view>
				<text class="font-md font-weight-bold" slot="center">已选中{{checkCount}}个</text>
				<view @click="handleCheckAll(true)" class="font-md mr-3 text-primary" slot="right">全选</view>
			</template>
		</nav-bar>
		<!-- 搜索框 -->
		<view class="px-3 py-2">
			<view class="position-relative">
				<view style="width: 70rpx;height: 70rpx;position: absolute;top: 0;left: 0;" class="flex align-center justify-center ">
					<text class="iconfont icon-sousuo text-light-muted"></text>
				</view>
				<input type="text" @input="search" value="" class=" bg-light fon-md rounded-circle" placeholder="搜索网盘文件" style="height: 70rpx;padding-left: 70rpx;" />
			</view>
		</view>

		<!-- 列表 -->
		<f-list @click=doEvent(item) @select="select" v-for="(item,index) in list" :item="item" :index="index" :key="index"></f-list>
		<!-- 底部操作条 -->
		<block v-if="checkCount>0">
			<view class="" style="height: 115rpx;">

			</view>
			<view class="flex fixed-bottom align-stretch bg-primary text-white" style="height: 110rpx;">

				<view hover-class="bg-hover-primary" @click="handleBottomEvent(item)" v-for="(item,index) in actions" :key="index"
				 class="flex flex-1 flex-column align-center justify-center" style="line-height: 1.5;">
					<text :class="item.icon" class="iconfont"></text>
					{{item.name}}
				</view>


			</view>
		</block>
		<!-- 是否要删除选中 -->
		<f-dialog ref="delete">是否要删除选中</f-dialog>
		<!-- 重命名 -->
		<f-dialog ref="rename">
			<input type="text" v-model="renamevalue" class="bg-light rounded flex-1 px-2" placeholder="重命名" style="height: 95rpx;"
			 value="" />
		</f-dialog>
		<!-- 新建文件夹 -->
		<f-dialog ref="newdir">
			<input type="text" v-model="newdirname" class="bg-light rounded flex-1 px-2" placeholder="新建文件夹名称" style="height: 95rpx;"
			 value="" />
		</f-dialog>
		<!-- 添加操作条 -->
		<uni-popup ref="add" type="bottom">
			<view class="bg-white flex" style="height: 200rpx;">
				<view @tap="handleAddEvent(item)" v-for="(item,index) in addList" :key="index" class="flex-1 flex flex-column align-center justify-center"
				 hover-class="bg-light">
					<text :class="[item.icon,item.color]" style="width: 110rpx;height: 110rpx;" class="rounded-circle bg-light iconfont  flex align-center justify-center"></text>
					<text class="font text-muted">{{item.name}}</text>
				</view>

			</view>
		</uni-popup>
		<!-- 排序框 -->
		<uni-popup ref="sort" type="bottom">
			<view class="bg-white">
				<view @click="changeSort(index)" v-for="(item,index) in sortOptions" :key="index" :class="index===sortIndex?'text-main':'text-dark'" hover-class="bg-light" class="border-bottom border-light-secondary flex align-center justify-center py-3 font">
					{{item.name}}
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import navBar from '@/components/common/nav-bar.vue';
	import fList from '@/components/common/f-list.vue';
	import fDialog from '@/components/common/f-dialog.vue';
	import uniPopup from '@/components/uni-ui/uni-popup/uni-popup.vue';

	export default {
		components: {
			navBar,
			fList,
			fDialog,
			uniPopup
		},
		
		data() {
			return {
				newdirname: '',
				sortIndex:0,
				sortOptions:[
					{
						name:'按名称排序',
						key:'name'
					},
					{
						name:'按时间排序',
						key:'created_time'
					}
				],
				addList: [{
						icon: 'icon-file-b-6',
						color: 'text-success',
						name: '上传图片'
					},
					{
						icon: 'icon-file-b-9',
						color: 'text-primary',
						name: '上传视频'
					},
					{
						icon: 'icon-file-b-8',
						color: 'text-muted',
						name: '上传文件'
					},
					{
						icon: 'icon-file-b-2',
						color: 'text-warning',
						name: '新建文件夹'
					},
				],
				renamevalue: '',
				title: 'Hello',
				list: [],
				dirs:[],
				limit:0
			}
		},
		computed: {
		
			// 选中的列表
			checkList() {
				return this.list.filter(item => item.checked)
			},
			// 选中的数量
			checkCount() {
				return this.checkList.length
			},
			// 文件id
			file_id(){
				let l=this.dirs.length
				if(l===0){
					return 0
				}else{
					return this.dirs[l-1].id
				}
			},
			current(){
				let l=this.dirs.length
				if(l===0){
					return false
				}else{
					return this.dirs[l-1]
				}
			},
			// 操作菜单
			actions() {
				if (this.checkCount > 1) {
					return [{
							icon: 'icon-xiazai',
							name: '下载'
						},
						{
							icon: 'icon-shanchu',
							name: '删除'
						}
					]
				} else {
					return [{
							icon: 'icon-xiazai',
							name: '下载'
						},
						{
							icon: 'icon-fenxiang-1',
							name: '分享'
						},
						{
							icon: 'icon-shanchu',
							name: '删除'
						},
						{
							icon: 'icon-chongmingming',
							name: '重命名'
						}
					]
				}
		
			}
		},
		onLoad() {
			this.dirs=uni.getStorageSync('dirs')?uni.getStorageSync('dirs'):[],
			this.getData()
		},
		methods: {
			formatList(list){
				return list.map(item=>{
					let type = 'none'
					if(item.isdir === 1){
						type = 'dir'
					} else {
						type = (item.ext.split('/'))[0] || 'none'
					}
					return {
						type,
						checked:false,
						...item
					}
				})
			},
			getData(){
				let order=this.sortOptions[this.sortIndex].key
				this.$H.get(`/file?file_id=${this.file_id}&orderby=${order}`,{token:true}).then(res=>{
					this.list=this.formatList(res)
				})
			},
			// 选中列表触发事件
			select(e) {
				this.list[e.index].checked = e.value
			},
			// 全选或取消全选
			handleCheckAll(checked) {
				this.list.forEach(item => item.checked = checked)
			},
			// 处理底部操作条事件
			handleBottomEvent(item) {
				switch (item.name) {
					case "删除":
						this.$refs.delete.open((close) => {
							uni.showLoading({
								title:'删除中'
							})
							let ids=(this.checkList.map(item=>item.id)).join(',')
							this.$H.post('/file/delete',{ids},{token:true}).then(res=>{
								this.getData()
								uni.showToast({
									title: '删除成功',
									icon: 'none'
								});
								uni.hideLoading()
							})
							close()
							
						});
						break;
					case "重命名":
						this.renamevalue = this.checkList[0].name
						this.$refs.rename.open((close) => {
							if (this.renamevalue == '') {
								return uni.showToast({
									title: '文件名称不能为空',
									icon: 'none'
								});
							}
							// 发起数据请求
							this.$H.post('/file/rename',{
								id:this.checkList[0].id,
								name:this.renamevalue,
								file_id:this.file_id
							},{token:true}).then(res=>{
								uni.showToast({
									title: '重名命成功',
									icon: 'none'
								});
								this.checkList[0].name = this.renamevalue
								this.handleCheckAll(false)
							})
							close()
							
						});
						break;
						case "下载":
						this.downloadFile()
						break;
						case "分享":
						this.share()
						break;
					default:
						break;
				}
			},
			handleAddEvent(item) {
				this.$refs.add.close()
				switch (item.name) {
					case "上传视频":
					uni.chooseVideo({
						count:1,
						success:(res)=>{
							let name=''
							let size=0
							// #ifndef H5
							name=res.tempFilePath.substring(res.tempFilePath.lastIndexOf('/')+1)
							// #endif
							// #ifdef H5
							name=res.tempFile.name
							// #endif
							this.upload({path:res.tempFilePath,name,type:'video',size:res.size},'video')
						}
					})
					break;
					case "上传图片":
					// 选择照片
					uni.chooseImage({
						count:9,
						success: (res) => {
							console.log(res)
							res.tempFiles.forEach(item=>{
								this.upload(item,'image')
							})
						}
					})
					break;
					case "新建文件夹":
						this.$refs.newdir.open((close) => {
							if (this.newdirname == '') {
								return uni.showToast({
									title: '文件名称不能为空',
									icon: 'none'
								});
							}
							// 发起数据请求
							this.$H.post('/file/createdir',{
								file_id:this.file_id,
								name:this.newdirname
							},{token:true}).then(res=>{
								uni.showToast({
									title: '新建文件夹成功',
									icon: 'none'
								});
								this.getData()
								close()
							})
						});
						break;
					default:
						break;
				}
			},
			// 打开添加操作条
			openAddDialog() {
				this.$refs.add.open()
			},
			openSortDialog(){
				this.$refs.sort.open()
			},
			doEvent(item){
				switch (item.type){
					case 'image': //预览图片
					let images=this.list.filter(item=>item.type==='image')
					uni.previewImage({
						current:item.url,
						urls:images.map(item=>item.url)
					});
					break;
					case 'video':
					console.log(item)
					uni.navigateTo({
						url:`../video/video?url=${item.url}&title=${item.name}`
					});
					break;
					
					
					default: 
					this.dirs.push({
						id:item.id,
						name:item.name
					})
					uni.setStorageSync('dirs',this.dirs)
					this.getData()
					
					break;
				}
			},
			back(){
				this.dirs.pop()
				uni.setStorageSync('dirs',this.dirs)
				this.getData()
				
			},
			changeSort(index){
				this.sortIndex=index
				
				this.getData()
				this.$refs.sort.close()
			},
			search(e){
				let keyword=e.detail.value
				if(keyword===''){
					return this.getData()
				}
				this.$H.get('/file/search?keyword='+keyword,{token:true}).then(res=>{
					this.list=this.formatList(res)
				})
			},
			  // 生成唯一id
			genID(length) {
			    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
			},
			share(){
				this.$H.post('/share/create',{file_id:this.checkList[0].id},{token:true}).then(res=>{
					uni.showModal({
						content: res,
						showCancel: true,
						confirmText: '复制分享',
						success: result => {
							// #ifndef H5
							uni.setClipboardData({
								data:res,
								success: () => {
									uni.showToast({
										title: '复制成功',
										icon: 'none'
									});
								}
							})
							// #endif
						},
					});
					this.handleCheckAll(false)
				})
			},
			downloadFile(){
				this.checkList.forEach(item=>{
					if(item.isdir===0){
						// 组织下载任务的参数
						let key=this.genID(8)
						// 组织上传数据
						let obj={
							name:item.name,
							type:item.type,
							size:item.size,
							key,
							progress:0,
							status:true,
							created_time:(new Date).getTime()
						} 
						// 创建上传任务
						this.$store.dispatch('createDownloadJob',obj)
						// 下载文件
						let url=item.url
						let d=uni.downloadFile({
							url,
							success: (res) => {
								if(res.statusCode===200){
									console.log('下载成功',res)
									// #ifndef H5
									uni.saveFile({
										tempFilePath:item.tempFilePath
									})
									// #endif
								}
							}
						})
						d.onProgressUpdate((res)=>{
							this.$store.dispatch('updateDownloadJob',{
								status:true,
								progress:res.progress,
								key
							})
						})
					}
					this.handleCheckAll(false)
					uni.showToast({
						title: '已加入下载任务',
						icon: 'none'
					});
				})
			},
			upload(file,type){
				let t=type
				const key=this.genID(8)
				let name=file.name
				if(!name){
					name=file.path.substring(file.path.lastIndexOf('/')+1)
				}
				// 组织上传数据
				let obj={
					name,
					type:t,
					size:file.size,
					key,
					progress:0,
					status:true,
					created_time:(new Date).getTime()
				}
				// 创建上传任务
				this.$store.dispatch('createUploadJob',obj)
				// 上传
				this.$H.upload('/upload?file_id='+this.file_id,{
					filePath:file.path
				},(p)=>{
					this.$store.dispatch('updateUploadJob',{
						status:true,
						progress:p,
						key
					})
				}).then(res=>{
					this.getData()
				})
				// 更新上传任务的监听
			},
		}
	}
</script>

<style>
page{
	overflow-x: auto;
}
</style>
